local thinkspeed = 0.1

AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")

include('shared.lua')

function ENT:Initialize ()
	self.Entity:PhysicsInit (SOLID_VPHYSICS)
	self.Entity:SetMoveType (MOVETYPE_VPHYSICS)
	self.Entity:SetSolid (SOLID_VPHYSICS)
	
	local phys = self.Entity:GetPhysicsObject()
	if phys:IsValid() then phys:Wake() end
	
	self.Direction = 0
end

function ENT:Think (force)
	local phys = self.Entity:GetPhysicsObject()
	local mass = phys:GetMass()
	if mass == 50000 then return end
	local omass = mass
	
	if phys:IsValid() then
		if self.Direction != 0 then
			print ("change")
			mass = math.max(math.min(mass + self.Direction * self.change_rate * thinkspeed, self.max_weight), self.min_weight)
		elseif self.auto_return == 1 then
			print ("autoreturn")
			if mass > self.default_weight then
				mass = math.max(mass - self.change_rate * thinkspeed, self.default_weight)
			else
				mass = math.min(mass + self.change_rate * thinkspeed, self.default_weight)
			end
		end
		print ("mass: "..mass.." ("..omass..")")
		if omass != mass or force then
			if mass == 50000 then mass = 50000.1 end
			phys:SetMass (math.max(math.min(mass, 10000000), 0.001))
			phys:Wake ()
			local plus = ""
			if self.Direction > 0 then plus = "+" end
			self:SetOverlayText ("Weight: "..math.floor(mass).." ("..plus..math.floor(self.change_rate) * self.Direction..")\nRange: "..math.floor(self.min_weight).."-"..math.floor(self.max_weight))
		end
	end
	self.Entity:NextThink (CurTime() + thinkspeed)
	return true
end

function ENT:ChangeStatus (dir, down)
	print ("..."..self.toggle)
	if tonumber(self.toggle) == 1 then
		print ("toggler")
		if not down then return end
		if self.Direction == dir then self.Direction = 0 else self.Direction = dir end
	else
		self.Direction = dir
	end
	print (self.Direction)
	self:Think (true)
end

local function Press (pl, ent, mul)
	if not ent:IsValid() then return false end
	ent:ChangeStatus (mul, true)
	return true
end

numpad.Register ("Weight_Press", Press)

local function Release (pl, ent, mul)
	if not ent:IsValid() then return false end
	ent:ChangeStatus (0, false)
	return true
end

numpad.Register ("Weight_Release", Release)